﻿using Newtonsoft.Json;
using SmarterCharger.Library.Infrastructure;
using SmarterCharger.Library.Model;
using SmarterCharger.Library.Repositories.Interfaces;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace SmarterCharger.Library.Repositories
{
    internal class SmartPlugRepository : ISmartPlugRepository
    {
        private const string SwitchSmartPlugUrl = "https://s-api.fifthplay.com/Web/api/Energy/SwitchSmartPlug";

        public async Task<HttpResponseResult> SwitchSmartPlug(SwitchSmartPlugRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");

            var switchSmartPlugRequest = GetSwitchSmartPlugRequest(request);

            using (var httpClient = new BasicAuthenticationHttpClient(request.Username, request.Password))
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var httpRequest = await httpClient.PostAsync(SwitchSmartPlugUrl, switchSmartPlugRequest);
                
                return new HttpResponseResult<IEnumerable<EnergyDevice>> { StatusCode = httpRequest.StatusCode };
            }
        }

        private StringContent GetSwitchSmartPlugRequest(SwitchSmartPlugRequest request)
        {
            var requestAsJson = JsonConvert.SerializeObject(new { SmartPlugId = request.SmartPlugId, Value = request.IsOn });
            
            return new StringContent(requestAsJson, Encoding.UTF8, "application/json");
        }
    }
}